#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSettings>
#include <QTimeLine>
#include <QDebug>
#include <QSound>

#include <QtCore/QCoreApplication>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_NFC_manager = new NFC(this);
    connect(m_NFC_manager,SIGNAL(sendUid(QByteArray)),this,SLOT(receiveUid(QByteArray)));
    init();


}

MainWindow::~MainWindow()
{
    delete ui;
    delete movie;
    delete mActivityObj;
    delete mTagObj;
    //delete m_pPlayer;
}

void MainWindow::setOrientation(ScreenOrientation orientation)
{
#if defined(Q_OS_SYMBIAN)
    // If the version of Qt on the device is < 4.7.2, that attribute won't work
    if (orientation != ScreenOrientationAuto) {
        const QStringList v = QString::fromAscii(qVersion()).split(QLatin1Char('.'));
        if (v.count() == 3 && (v.at(0).toInt() << 16 | v.at(1).toInt() << 8 | v.at(2).toInt()) < 0x040702) {
            qWarning("Screen orientation locking only supported with Qt 4.7.2 and above");
            return;
        }
    }
#endif // Q_OS_SYMBIAN

    Qt::WidgetAttribute attribute;
    switch (orientation) {
#if QT_VERSION < 0x040702
    // Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes
    case ScreenOrientationLockPortrait:
        attribute = static_cast<Qt::WidgetAttribute>(128);
        break;
    case ScreenOrientationLockLandscape:
        attribute = static_cast<Qt::WidgetAttribute>(129);
        break;
    default:
    case ScreenOrientationAuto:
        attribute = static_cast<Qt::WidgetAttribute>(130);
        break;
#else // QT_VERSION < 0x040702
    case ScreenOrientationLockPortrait:
        attribute = Qt::WA_LockPortraitOrientation;
        break;
    case ScreenOrientationLockLandscape:
        attribute = Qt::WA_LockLandscapeOrientation;
        break;
    default:
    case ScreenOrientationAuto:
        attribute = Qt::WA_AutoOrientation;
        break;
#endif // QT_VERSION < 0x040702
    };
    setAttribute(attribute, true);
}

void MainWindow::showExpanded()
{
#if defined(Q_OS_SYMBIAN) || defined(Q_WS_SIMULATOR)
    showFullScreen();
#elif defined(Q_WS_MAEMO_5)
    showMaximized();
#else
    show();
#endif
}

void MainWindow::init()
{
    qDebug()<<"Init of program";
    mUistate= LockedState;
    movie = new QMovie(":/dish3.gif");
    ui->NFC_label->setMovie(movie);
    mActivityObj=NULL;
    mTagObj=NULL;
    mDialog=NULL;
    mAudioFeedback=true;
    mNetworkTimeOut=false;

    newActivity();
    initActivityView();
    readSettings();
    //m_pPlayer = new QMediaPlayer(this); connect(m_pPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(statusChanged(qint64)));
}

void MainWindow::newActivity()
{

    if(mActivityObj)
        delete mActivityObj;

    if (mTagObj)
        delete mTagObj;



    //Create the activity object, and connect the update signal, to the statemashine slot
    //This is called everytime a tag is scanned, and result has been found.
    mActivityObj = new Activity(this);
    connect(mActivityObj,SIGNAL(update(Activity::ActivityStatus)),this,SLOT(activityUpdate(Activity::ActivityStatus)));
    connect(mActivityObj,SIGNAL(timeoutProgress(int)),this,SLOT(timeOut(int)));

    //********************************************************************************************************
    mTagObj = new TagDataRequest(this);
    connect(mTagObj,SIGNAL(updateActivity(Participant*, QByteArray ,QString,QDateTime,QDateTime,int)),mActivityObj,SLOT(dataUpdated(Participant*, QByteArray ,QString,QDateTime,QDateTime,int)));
    connect(mTagObj,SIGNAL(updateActivityParticipent(Participant*)),mActivityObj,SLOT(participantUpdated(Participant*)));
    connect(mTagObj, SIGNAL(participantAdd(Participant*)), mActivityObj, SLOT(participantAdd(Participant*)));
    connect(mTagObj,SIGNAL(activityUpdatedSignal(Activity::ActivityStatus)),mActivityObj,SLOT(activityUpdated(Activity::ActivityStatus)));
    connect(mTagObj,SIGNAL(activityOrganiserSignal(Participant*,QByteArray)),mActivityObj,SLOT(organiserSignal(Participant*,QByteArray)));








    ui->stackedWidget->setCurrentIndex(0);


}

//**************************************************************************************
//Function to read and write setting to ini file
void MainWindow::writeSettings()
{
    mIPAddr=ui->ipaddr->text();
    QSettings settings("nfcdemo");

    settings.beginGroup("userdata");
    settings.setValue("ipaddr",mIPAddr);
    settings.setValue("audioFeedback",mAudioFeedback);
    //settings.setValue("userid",mUserid);
    //settings.setValue("password",mPassword);
    //settings.setValue("alarmOn",mAlarmOn);
    //settings.setValue("calendarOn",mCalendarOn);
    //settings.setValue("alarmOffset",mAlarmOffset);

    settings.endGroup();

}
void MainWindow::readSettings()
{
    QSettings settings("nfcdemo");
    settings.beginGroup("userdata");
    mIPAddr=settings.value("ipaddr").toString();
    mAudioFeedback=settings.value("audioFeedback").toBool();

    //mUserid=settings.value("userid").toString();
    //mPassword=settings.value("password").toString();
    //mAlarmOn=settings.value("alarmOn").toBool();
    //mCalendarOn=settings.value("calendarOn").toBool();
    //mAlarmOffset=settings.value("alarmOffset").toInt();
    settings.endGroup();

   ui->ipaddr->setText(mIPAddr);
   ui->soundFeedback->setChecked(mAudioFeedback);


}
void MainWindow::feedBack()
{

    QFeedbackEffect::playThemeEffect(QFeedbackEffect::ThemeBasicButton);
    //Select a file
    // m_pPlayer->setMedia(QUrl::fromLocalFile("e:\\Sounds\\Digital\\NFC.mp3"));
    //Set the volume
    // m_pPlayer->setVolume(50);
    // m_pPlayer->play();



}




//All slot function should go below this line
//Slot functions

//Frames for doing in animations
//************************************************************************
void MainWindow::setSettingsFrameTrans(int aValue)
{
    QPalette palette = ui->settings_frame->palette();
    palette.setColor( backgroundRole(), QColor( 255,255, 255,aValue ) );
    ui->settings_frame->setPalette( palette );
    ui->settings_frame->setAutoFillBackground( true );

}

void MainWindow::setLockedFrameTrans(int aValue)
{
    QPalette palette = ui->locked_frame->palette();
    palette.setColor( backgroundRole(), QColor( 255,255, 255,aValue ) );
    ui->locked_frame->setPalette( palette );
    ui->locked_frame->setAutoFillBackground( true );


}

void MainWindow::setUnLockedFrameTrans(int aValue)
{
    //    QPalette palette = ui->frame_7->palette();
    //    palette.setColor( backgroundRole(), QColor( 255,255, 255,aValue ) );
    //    ui->frame_7->setPalette( palette );
    //    ui->frame_7->setAutoFillBackground( true );


}

void MainWindow::setActivityFrameTrans(int aValue)
{
    QPalette palette = ui->activity_frame->palette();
    palette.setColor( backgroundRole(), QColor( 255,255, 255,aValue ) );
    ui->activity_frame->setPalette( palette );
    ui->activity_frame->setAutoFillBackground( true );

}


void MainWindow::setUnRegActivityFrameTrans(int aValue)
{

    QPalette palette = ui->unreg_activity_frame->palette();
    palette.setColor( backgroundRole(), QColor( 255,255, 255,aValue ) );
    ui->unreg_activity_frame->setPalette( palette );
    ui->unreg_activity_frame->setAutoFillBackground( true );

}

//************************************************************************

void MainWindow::statusChanged(QMediaPlayer::MediaStatus status)
{
    if ( (QMediaPlayer::LoadedMedia == status) && m_pPlayer)
    {
        m_pPlayer->play();
    }
}







void MainWindow::on_pushButton_clicked()
{
    //Starting the NFC reader
    setUnRegActivityFrameTrans(255);
    ui->unreg_activity_frame->update();
    QTimeLine *timeLine = new QTimeLine(1000, this);
    timeLine->setFrameRange(255, 0);
    connect(timeLine, SIGNAL(frameChanged(int)), this,SLOT(setUnRegActivityFrameTrans(int)));
    timeLine->start();
    ui->headerLabel->setText("Un Reg Activity");
    ui->stackedWidget->setCurrentIndex(3);

    ui->Exit->setText("Back");
    updateState(Ureg_ActivityState);


}

void MainWindow::receiveUid(QByteArray mUid)
{
    //call statemashine and do something.
//    if(mAudioFeedback)
//        QSound::play("callended.wav");
    feedBack();

    //    QApplication::beep();

    qDebug("Receiving NFC ID");
    m_NFCUID=mUid;
    updateState(ScannedTag);

}



void MainWindow::on_Exit_clicked()
{
    qDebug()<<"Ui state = "<<mUistate;
    QFeedbackEffect::playThemeEffect(QFeedbackEffect::ThemeBasic);
    if ((mUistate==SettingsState)||(mUistate==ActivityState)||(mUistate==Ureg_ActivityState)||(mUistate==RegTimeOutState)||(mUistate==Ureg_ActivityState))
    {


        //Store setting if we come from settings state;
        if (mUistate==SettingsState)
        {
            writeSettings();
        }
        clearActivityView();
        newActivity();
        updateState(LockedState);




    }
    else if ((mUistate==ActivityWaitForScanningState)||(mUistate==ActivityUpdateStudent)||(mUistate==ActivityDialogWaitState))
    {
        qDebug()<<"Back key pressed in dialog state, No action";
    }

    else
    {
        close();
    }
}

void MainWindow::on_settings_2_clicked()
{
    QFeedbackEffect::playThemeEffect(QFeedbackEffect::ThemeBasic);
    if (mUistate!=SettingsState) //Do not react to more than press
    {

        setSettingsFrameTrans(255);
        ui->activity_frame->update();
        QTimeLine *timeLine = new QTimeLine(1000, this);
        timeLine->setFrameRange(255, 0);
        connect(timeLine, SIGNAL(frameChanged(int)), this,SLOT(setSettingsFrameTrans(int)));
        timeLine->start();
        ui->headerLabel->setText("Settings");
        ui->stackedWidget->setCurrentIndex(4);

        ui->Exit->setText("Back");
        updateState(SettingsState);
    }

}

void MainWindow::on_pushButton_2_clicked()
{

     ui->stackedWidget->setCurrentIndex(3);
}

void MainWindow::on_pushButton_3_clicked()
{

    setActivityView();
}


void MainWindow::on_soundFeedback_clicked(bool checked)
{
    feedBack();
    mAudioFeedback=checked;
}

void MainWindow::playStudentTag()
{
    if(mAudioFeedback)
        QSound::play("ok1.wav");
}

void MainWindow::playTeacherTag()
{
    if(mAudioFeedback)
        QSound::play("ok1.wav");
}

void MainWindow::playError()
{

    if(mAudioFeedback)
    {
     qDebug()<<"Play audio";
        QSound::play("error.wav");
    }
}
